package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.anno.Log;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.Emp;
import com.itheima.pojo.PageBean;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmpServiceImpl implements EmpService {
    @Autowired
    private EmpMapper empMapper;

    /*
    1.根据页码和每页显示条数，自动生成”limit?,?“ 片段
    2.将上述生成的”limit?,?“ 片段，拼接到mapper的原生sql的后面，查询之后的结果会自动赋值到pageInfo对象中
    3.基于基础sql，改造出一条 count(0)求总数的sql，并自动帮你发送，自动将返回值赋值给pageInfo对象中
     */
    @Override
    public PageBean page(String name, Short gender, LocalDate begin, LocalDate end, Integer page, Integer pageSize) {
        //他们都是同一个线程执行的代码。线程对象可以存储数据的，ThreadLocal本地线程对象(工具)
        //1.设置分页参数
        Page<Emp> pageInfo = PageHelper.startPage(page, pageSize);//limit 0,10
        //2.调用mapper分页员工集合
        empMapper.page(name,gender,begin,end);
        //3.返回PageBean数据
        return new PageBean(pageInfo.getTotal(),pageInfo.getResult());
    }

    @Override
    @Log
    public void deleteByIds(List<Integer> ids) {
        empMapper.deleteByIds(ids);
    }

    @Override
    @Log
    public void save(Emp emp) {
        //1.完善数据
        emp.setPassword("123456");
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        //2.保存
        empMapper.save(emp);
    }

    @Override
    public Emp findById(Integer id) {
        return empMapper.findById(id);
    }

    @Override
    @Log
    public void update(Emp emp) {
        //1.完善数据
        emp.setUpdateTime(LocalDateTime.now());
        //2.修改
        empMapper.update(emp);
    }

    @Override
    public Emp login(Emp emp) {
        //select * from emp where username=#{username} and password=#{password}
        Emp e = empMapper.findByUsernameAndPassword(emp);
        return e;
    }
}
